package com.redis.controller;

import cn.hutool.json.JSONUtil;
import com.redis.model.PubSub;
import com.redis.model.User;
import com.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Redis操作
 * @author YI
 * @date 2018-3-20 16:15:53
 */
@Controller
@RequestMapping("/redis")
public class RedisCrontroller {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RedisService redisService;


    /**
     * 往redis中写入数据
     * @return
     */
    @RequestMapping("/simpleSet")
    @ResponseBody
    public String simpleSet(){
        User user = new User("12345", "张三", 99.9);

        redisService.save("user", JSONUtil.toJsonPrettyStr(user));
        return "Success";
    }

    /**
     * 读取redis中的数据
     * @return
     */
    @RequestMapping("/simpleGet")
    @ResponseBody
    public List simpleGet(){
        List<Object> list = new ArrayList<>();
        String user = redisTemplate.opsForValue().get("user");
//        ArrayList<User> users = JSONUtil.parseArray(user).toList(User.class);
        list.add(JSONUtil.toBean(user, User.class));
        return list;
    }

    /**
     * 发送消息 支持基于Redis的消息订阅/发布消息
     * @return
     */
    @RequestMapping("/pub")
    @ResponseBody
    public String pub(String message) {
        //推送遵从news.*的格式 接受处理
        redisTemplate.convertAndSend(PubSub.NEWSTEST.getChannel(), message);

        return "Success";
    }

    /**
     *  地理信息查询
     */
    @RequestMapping("/geo")
    @ResponseBody
    public List geo() {
        return redisService.redisGeo();
    }

    /**
     * 根据权重进行排名
     */
    @RequestMapping("/sortSet")
    @ResponseBody
    public List sortSet(){
        return redisService.sortSet();
    }
}
